package bll

import (
	"errors"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/util"
	"time"
)

// UserType 用户类型管理
type UserType struct {
	UserTypeModel model.IUserType `inject:"IUserType"`
}

// QueryPage 查询分页数据
func (a *UserType) QueryPage(params schema.UserTypeQueryParam, pageIndex, pageSize uint) (int64, []*schema.UserTypeQueryResult, error) {
	return a.UserTypeModel.QueryPage(params, pageIndex, pageSize)
}

// QuerySelect 查询选择数据
func (a *UserType) QuerySelect(params schema.UserTypeSelectParam) ([]*schema.UserTypeSelect, error) {
	return a.UserTypeModel.QuerySelect(params)
}

// Get 精确查询数据
func (a *UserType) Get(recordID string) (*schema.UserType, error) {
	return a.UserTypeModel.Get(recordID)
}

// GetByCode 根据编号获取数据
func (a *UserType) GetByCode(code string) (*schema.UserType, error) {
	return a.UserTypeModel.GetByCode(code)
}

// Create 创建数据
func (a *UserType) Create(item *schema.UserType) error {
	exists, err := a.UserTypeModel.CheckCode(item.Code)
	if err != nil {
		return err
	} else if exists {
		return errors.New("用户类型编号已经存在")
	}

	item.ID = 0
	item.RecordID = util.UUID()
	item.Created = time.Now().Unix()
	item.Deleted = 0
	return a.UserTypeModel.Create(item)
}

// Update 更新数据
func (a *UserType) Update(recordID string, item *schema.UserType) error {
	oldItem, err := a.Get(recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.New("无效的数据")
	}

	if item.Name != oldItem.Name {
		exists, verr := a.UserTypeModel.CheckCode(item.Code)
		if verr != nil {
			return verr
		} else if exists {
			return errors.New("用户类型编号已经存在")
		}
	}

	info := util.StructToMap(item)
	delete(info, "id")
	delete(info, "record_id")
	delete(info, "creator")
	delete(info, "created")
	delete(info, "deleted")

	return a.UserTypeModel.Update(recordID, info)
}

// UpdateStatus 更新状态
func (a *UserType) UpdateStatus(recordID string, status int) error {
	info := map[string]interface{}{
		"status": status,
	}
	return a.UserTypeModel.Update(recordID, info)
}

// Delete 删除数据
func (a *UserType) Delete(recordID string) error {
	return a.UserTypeModel.Delete(recordID)
}

// QueryAll 查询全部数据
func (a *UserType) QueryAll(params schema.UserTypeQueryParam) ([]*schema.UserTypeQueryResult, error) {
	var (
		num    int64
		result []*schema.UserTypeQueryResult
		err    error
	)
	num, _, err = a.UserTypeModel.QueryPage(params, 1, 0)

	if err != nil {
		return nil, err
	}

	_, result, err = a.UserTypeModel.QueryPage(params, 1, uint(num))

	return result, err
}
